import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image, Button } from '@tarojs/components'
import './doctorcertified.css'
import { AtInput, AtForm, AtList, AtListItem, AtImagePicker, AtButton, AtIcon, AtRadio, AtTag } from 'taro-ui'
import reactMixin from 'react-mixin';
import myJs from './doctorcertifiedJs.js'
import app from '../../../../main.js'
import { doc } from 'nerv-utils';

export default class DoctorCertified extends Component {
  config = {
    navigationBarTitleText: '医生认证'
  }

  constructor() {
    super(...arguments);
    this.state = {
      doctor: {},
      head_images: [],
      info: '',
      positions: [],
      hospitalProvince: {},
      hospitals: [[], [], []],
      departments:[],
      defaultDepartments:'请输入科室名称',
      chest_card_pics: [],
      qualification_pics: [],
      genders: ['男', '女'],
      hospitals2: []
    }
  }

  init() { 
    this.doctor();
    this.getPositions();
    this.initHospitals();
    this.getDepartments();
  }

  getDepartments() {
    let me = this;
    app.get('web/yun_xue_yuan/departments', {}, function(res) {
      me.setState({
        departments: res.data.result.list
      });
    });
  }
  setInfo() {
    let info = '';
    if (this.state.doctor.auth_status == '申请中') {
      info = '正在审核中';
    } else if (this.state.doctor.auth_status == '审核不通过') {
      info = '审核不通过';
    } else if (this.state.doctor.auth_status == '审核通过') {
      info = '审核通过';      
    } else if (this.state.doctor.auth_status == '未认证') {
      info = '还未认证';      
    }
    console.log('info='+info);
    this.setState({
      info: info
    });
  }
  getPositions() {
    let me = this;
    app.get('web/yun_xue_yuan/positions', {}, function(res) {
      me.setState({
        positions: res.data.result.list
      });
    });
  }
  // 选择省市
  selectPositionCity(e){
    var me = this;
    let doctor = this.state.doctor
    doctor.province = e.detail.value.find((n,index) => index ==0 )
    doctor.city = e.detail.value.find((n,index2)=>index2 == 1)
    doctor.hospital = '';
    this.setState({
      doctor:doctor
    })
    app.get('web/hospital/all', {province: doctor.province, city: doctor.city}, function(res) {
      console.log(res)
      me.setState({
        hospitals2: res.data.result,
      })
    })
  }
  selectPosition(e) {
    let doctor = this.state.doctor;
    doctor.positional_title = this.state.positions[e.detail.value].positional_title;
    doctor.positional_title_id = this.state.positions[e.detail.value].positional_title_id;
    this.setState({
      doctor: doctor
    });
  }
  // 初始化医院
  initHospitals() {
    var me = this;
    app.get('web/hospital/provinces', {}, function(res) {
      var hospitals = me.state.hospitals;
      var provinces = res.data.result;
      var province = provinces[0];
      hospitals[0] = provinces;

      app.get('web/hospital/cities', {province_id: province.id}, function(res) {
        var cities = res.data.result;
        hospitals[1] = cities;

        app.get('web/hospital/all', {province: province.name, city: cities[0].name}, function(res) {
          hospitals[2] = res.data.result;
          me.setState({
            hospitals: hospitals,
            hospitalProvince: province
          })
        })
      })
    })
  }
  // 初始医院2
  initHospitals2(province, city) {
    var me = this;
    app.get('web/hospital/all', {province: province, city: city}, function(res) {
      console.log(res)
      me.setState({
        hospitals2: res.data.result,
      })
    })
  }
  // 选择医院
  selectHospital(e) {
    var value = e.detail.value;
    var hospital = this.state.hospitals[2][value[2]];
    var doctor = this.state.doctor;
    doctor.hospital_id = hospital.id;
    doctor.hospital = hospital.name;
    this.setState({
      doctor: doctor
    })
  }
  // 选择医院2
  selectHospital2(e) {
    console.log(e);
    var value = e.detail.value;
    var hospital = this.state.hospitals2[value];
    var doctor = this.state.doctor;
    doctor.hospital_id = hospital.id;
    doctor.hospital = hospital.name;
    this.setState({
      doctor: doctor
    })
  }
  // 改变医院
  changeHospital(e) {
    var me = this;
    var column = e.detail.column;
    var value = e.detail.value;
    var hospitals = me.state.hospitals;
    
    if (column == 0) {
      Taro.showLoading();
      var province = hospitals[0][value];
      app.get('web/hospital/cities', {province_id: province.id}, function(res) {
        var cities = res.data.result;
        hospitals[1] = cities;
        me.setState({
          hospitals: hospitals,
          hospitalProvince: province
        })

        app.get('web/hospital/all', {province: province.name, city: cities[0].name}, function(res) {
          hospitals[2] = res.data.result;
          me.setState({
            hospitals: hospitals
          })
          Taro.hideLoading();
        })
      })
    } else if (column == 1) {
      Taro.showLoading();
      var province = this.state.hospitalProvince;
      var city = hospitals[1][value];
      app.get('web/hospital/all', {province: province.name, city: city.name}, function(res) {
        hospitals[2] = res.data.result;
        me.setState({
          hospitals: hospitals,
          hospitalProvince: province
        })
        Taro.hideLoading();
      })
    }
  }
  // 选择科室
  setdepartments (e) {
    let doctor = this.state.doctor
    let index = e.detail.value
    doctor.department = this.state.departments[index].department;
    doctor.department_id = this.state.departments[index].department_id;
    this.setState({
      doctor: doctor
    })
  }
  doctor() {
    let me = this;
    app.get('web/doctor/get', {}, function(res) {
      let doctor = res.data.result;
      me.initHospitals2(doctor.province, doctor.city);
      me.setState({
        doctor: doctor,
        qualification_pics: me.filesToArr(doctor.qualification_pics),
        chest_card_pics: me.filesToArr(doctor.chest_card_pics)
      }, () => {
        me.setInfo();
      });
    });
  }
  check() {
    let me = this;
    app.get('web/doctor/get', {}, function(res) {
      let doctor = res.data.result;
      if (doctor.auth_status == '审核通过') {
        app.redirectTo('/pages/doctorpages/homepage/homepage')
      }
    });
  }
  save() {
    let me = this;
    let doctor = this.state.doctor;

    if (app.isEmpty(doctor.head_image)) {
      app.toast('请上传头像');
      return;
    }
    if (app.isEmpty(doctor.name)) {
      app.toast('请输入姓名');
      return;
    }
    if (app.isEmpty(doctor.gender) || doctor.gender == '未知') {
      app.toast('请选择性别');
      return;
    }
    if (app.isEmpty(doctor.phone)) {
      app.toast('请输入手机号');
      return;
    }
    if (!app.checkPoneFormat(doctor.phone)) {
      app.toast('手机号码格式不正确');
      return;
    }
    if (app.isEmpty(doctor.positional_title)) {
      app.toast('请选择职称');
      return;
    }
    if (app.isEmpty(doctor.city)) {
      app.toast('请选择省市');
      return;
    }
    if (app.isEmpty(doctor.hospital)) {
      app.toast('请选择医院');
      return;
    }
    if (app.isEmpty(doctor.department)) {
      app.toast('请选择科室');
      return;
    }
    if (app.isEmpty(doctor.good_at)) {
      app.toast('请选择擅长领域');
      return;
    }
    if (me.state.qualification_pics.length == 0 && me.state.chest_card_pics.length == 0) {
      app.toast('请上传医师资格证照片 或者 医院胸牌照片');
      return;
    }    
    doctor.qualification_pics = this.filesToStr(me.state.qualification_pics);
    doctor.chest_card_pics = this.filesToStr(me.state.chest_card_pics);
    doctor.auth_status = '申请中';
    app.post('web/doctor/save', doctor, function(res) {
      let data = res.data;
      if (data.status == 200) {
        var dct = me.state.doctor;
        dct.auth_status = '申请中';
        me.setState({
          doctor: dct
        }, () => {
          me.setInfo();
        });
        app.success('提交成功', ()=> {
          app.redirectTo('/pages/center/pages/doctorstatus/doctorstatus');
        });

      } else {
        app.title('提交失败');
      }
    });
  }
  filesToStr(files) {
    let arr = [];
    for (let i = 0; i < files.length; i++) {
      arr.push(files[i].url);
    }
    return JSON.stringify(arr);
  }

  filesToArr(str) {
    let files = [];
    try {
      let arr = JSON.parse(str);
      for (let i = 0; i < arr.length; i++) {
        let item = {url: arr[i]};
        files.push(item);
      }
    } catch (error) {
      console.log('error', error, str);
    }
    return files;
  }
  changeZige(files, operationType, index) {
    let me = this;
    if (operationType == 'add') {
      Taro.showLoading({
        title: '上传中...',
        mask: true
      });
      Taro.uploadFile({
        url: app.apiUri + '/admin/upload/image',
        filePath: files[files.length - 1]['url'],
        name: 'file',
        formData: {
          name: 'file'
        },
        success(res) {
          Taro.hideLoading();
          if (res.statusCode == 413) {
            app.toast('文件过大，请重新上传');
            return;
          }
          let data = JSON.parse(res.data);
          if (data.status == 200) {
            let item = {url: app.getPath(data.result)}
            var qualification_pics = me.state.qualification_pics;
            qualification_pics.push(item);
            me.setState({
              qualification_pics: qualification_pics
            });
          }
        }
      })
    } else if (operationType == 'remove') {
      let qualification_pics = me.state.qualification_pics;
      qualification_pics.splice(index, 1);
      me.setState({
        qualification_pics: qualification_pics
      });
    }
  }
  changeChest(files, operationType, index) {
    let me = this;
    if (operationType == 'add') {
      Taro.showLoading({
        title: '上传中...',
        mask: true
      });
      Taro.uploadFile({
        url: app.apiUri + '/admin/upload/image',
        filePath: files[files.length - 1]['url'],
        name: 'file',
        formData: {
          name: 'file'
        },
        success(res) {
          Taro.hideLoading();
          if (res.statusCode == 413) {
            app.toast('文件过大，请重新上传');
            return;
          }
          let data = JSON.parse(res.data);
          if (data.status == 200) {
            let item = {url: app.getPath(data.result)}
            let chest_card_pics = me.state.chest_card_pics;
            chest_card_pics.push(item);
            me.setState({
              chest_card_pics: chest_card_pics
            })
          }
        }
      })
    } else if (operationType == 'remove') {
      let chest_card_pics = me.state.chest_card_pics;
      chest_card_pics.splice(index, 1);
      me.setState({
        chest_card_pics: chest_card_pics
      })
    }
  }
  uploadHeadImage() {
    var me = this;
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        Taro.uploadFile({
          url: app.apiUri + '/admin/upload/image',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            name: 'file'
          },
          success(res) {
            if (res.statusCode == 413) {
              app.toast('文件过大，请重新上传');
              return;
            }
            let data = JSON.parse(res.data);
            if (data.status == 200) {
              let doctor = me.state.doctor;
              doctor.head_image = data.result;
              me.setState({
                doctor: doctor
              });
            }
          }
        })
      }
    })
  }
  selectGender(e) {
    let doctor = this.state.doctor;
    doctor.gender = this.state.genders[e.detail.value];
    this.setState({
      doctor: doctor
    });
  }
  selectLabel(item) {
    var doctor = this.state.doctor;
    var good_at_labels = doctor.good_at_labels;
    for (var i = 0; i < good_at_labels.length; i++) {
      if (good_at_labels[i]['id'] == item['id']) {
        good_at_labels[i]['active'] = !good_at_labels[i]['active'];
      }
    }
    doctor.good_at_labels = good_at_labels;
    // good_at 字段组装成数组
    var good_at = [];
    for (var i = 0; i < good_at_labels.length; i++) {
      var item = good_at_labels[i];
      if (item['active']) {
        good_at.push(item['id']);
      }
    }
    doctor.good_at = JSON.stringify(good_at);
    this.setState({
      doctor: doctor
    });
  }

  render() {
    return (
      <View className='doctor-certified'>
        {
          this.state.info 
          && 
          <View className='info'>{this.state.info}</View>
        }
        <View className='v_head_image'>
          <Image className='head_image' src={app.getPath(this.state.doctor.head_image)}></Image>
          <Button className='btn_upload' onClick={this.uploadHeadImage}>上传头像</Button>
        </View>
        <AtInput
          className='line'
          name='value'
          title='姓名'
          type='text'
          placeholder='请输入姓名'
          value={this.state.doctor.name}
          onChange={this.handleChange.bind(this, 'doctor.name')}
        />
        <View className='page-section form_item'>
          <View className='label'>性別</View>
          <View className='select'>
            <Picker mode='selector' range={this.state.genders} onChange={this.selectGender}>
              <View className='picker'>
                {
                  (!this.state.doctor.gender || this.state.doctor.gender == '未知')
                  ?
                  "请选择性別"
                  :
                  this.state.doctor.gender
                }
              </View>
            </Picker>
          </View>
        </View>
        <AtInput
          className='line'
          name='value'
          title='手机号'
          type='text'
          placeholder='请输入手机号'
          value={this.state.doctor.phone}
          onChange={this.handleChange.bind(this, 'doctor.phone')}
        />
        <View className='page-section form_item'>
          <View className='label'>职称</View>
          <View className='select'>
            <Picker mode='selector' range={this.state.positions} rangeKey='positional_title' onChange={this.selectPosition}>
              <View className='picker'>
                {
                  !this.state.doctor.positional_title
                  ?
                  "请选择职称"
                  :
                  this.state.doctor.positional_title
                }
              </View>
            </Picker>
          </View>
        </View>
        <View className='page-section form_item'>
          <View className='label'>省市</View>
          <View className='select'>
            <Picker mode='region' onChange={this.selectPositionCity.bind(this)}>
              <View className='picker'>
                {
                  app.isEmpty(this.state.doctor.province) && app.isEmpty(this.state.doctor.city)
                  ?
                  "请选择省市"
                  :
                  this.state.doctor.province + this.state.doctor.city
                }
              </View>
            </Picker>
          </View>
        </View>
        <View className='page-section form_item'>
          <View className='label'>医院</View>
          <View className='select'>
            <Picker mode='selector' range={this.state.hospitals2} rangeKey='name' onChange={this.selectHospital2}>
              <View className='picker'>
                {
                  !this.state.doctor.hospital
                  ?
                  "请选择医院"
                  :
                  this.state.doctor.hospital
                }
              </View>
            </Picker>
          </View>
        </View>
        {/* <View className='page-section form_item'>
          <View className='label'>医院</View>
          <View className='select'>
            <Picker mode='multiSelector' range={this.state.hospitals} rangeKey='name' onColumnChange={this.changeHospital} onChange={this.selectHospital}>
              <View className='picker'>
                {
                  !this.state.doctor.hospital
                  ?
                  "请选择医院"
                  :
                  this.state.doctor.hospital
                }
              </View>
            </Picker>
          </View>
        </View> */}
        <View className='page-section form_item'>
          <View className='label'>科室</View>
          <View className='select'>
            <Picker mode='selector' range={departments} rangeKey='department' onChange={this.setdepartments.bind(this)}>
              <View className='picker'>
                {
                  !this.state.doctor.department
                  ?
                  "请选择科室"
                  :
                  this.state.doctor.department
                }
              </View>
            </Picker>
          </View>
        </View>
        <View class='tag'>
          <View class='label'>擅长</View>
          <View class='content'>
            {
              this.state.doctor.good_at_labels.map((item) => {
                return (<View class='item_tag'><AtTag active={item.active} onClick={this.selectLabel.bind(this, item)}>{item.title}</AtTag></View>)
              })
            }
          </View>
        </View>
        <AtListItem title='认证方式1: 医师资格证照片' hasBorder={false} />
        <AtImagePicker
          className='line upload-img'
          count={1}
          files={this.state.qualification_pics}
          onChange={this.changeZige.bind(this)}
        />
        <AtListItem title='认证方式2: 医院胸牌照片' hasBorder={false} />
        <AtImagePicker
          className='line upload-img'
          count={1}
          files={this.state.chest_card_pics}
          onChange={this.changeChest.bind(this)}
        />
        <View className='blank-box'></View>
        <View className='btn'>
          <AtButton type='primary' full size='normal' className='btn-son' onClick={this.save.bind(this)}>
            提交
          </AtButton>
        </View>
      </View>
    )
  }
}
reactMixin.onClass(DoctorCertified, myJs);
